package com.shop.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.WeChatUser.UserLoginDto;
import com.shop.entity.pojo.User;
import com.shop.entity.vo.UserLoginVo;
import com.shop.user.mapper.UserMapper;
import com.shop.user.service.UserService;
import com.shop.utils.common.enums.*;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.HttpClientUtil;
import com.shop.utils.config.LoginFailedException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;

@Service

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Autowired
    private UserMapper userMapper;

    private static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public Result<UserLoginVo> Login(UserLoginDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", WeChat.WeChat_Login_token.getAppid());
        map.put("secret",WeChat.WeChat_Login_token.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        if (openid==null) {
           throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getOpenId,openid));
        if (user==null) {
            user=User.builder().openId(openid).createTime(String.valueOf(LocalDateTime.now())).build();
            boolean adduser = userMapper.adduser(user);
            if (!adduser) {
                throw new LoginFailedException(MessageConstant.UPLOAD_FAILED);
            }
        }
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Alg, Jwt.WeChat_Jwt_Key.getAlg()) //令牌类型
                .setHeaderParam(Message.Jwt_Typ, Jwt.WeChat_Jwt_Key.getTyp()) //签名算法
                .setSubject(Jwt.WeChat_Jwt_Key.getName()) // 令牌主题
                .setExpiration(new Date(System.currentTimeMillis() + Jwt.WeChat_Jwt_Key.getExp())) // 设置过期时间
                .claim(Message.User_Id,user.getId() ) // 私有字段
                .signWith(SignatureAlgorithm.HS256, Jwt.WeChat_Jwt_Key.getKey())//签名哈希
                .compact(); //转换成字符串
        UserLoginVo userLoginVo=new UserLoginVo();
        userLoginVo.setId(user.getId());
        userLoginVo.setToken(token);
        return Result.okResult(userLoginVo);
    }
}
